/**
 * Created by Ysssssss on 2021/4/1.
 */
import React, { useState, forwardRef, createContext, useImperativeHandle, useContext, useMemo, useCallback, useEffect } from 'react';
import { Table, Pagination, Empty } from "antd";
import {useHistory} from "react-router";
import {getQuery} from "@utils/setUrlQuery";
import OrderLine from "@common/presentational/OrderLine";


const CustomizeTableContext = createContext()

const CustomizeTableProvide = (props, ref) => {
    const { children, tableKey, onChange } = props
    const history = useHistory()
    const { pageNo: pageNoInit = 1, pageSize: pageSizeInit = 20 } = getQuery(history)
    const [{ current, pageSize }, setTablePage] = useState({ current: parseInt(pageNoInit), pageSize: parseInt(pageSizeInit) })
    const _setTablePage = params => setTablePage(preState => ({
        ...preState,
        ...params,
    }))

    useEffect(() => {
        onChange && onChange({
            current,
            pageSize
        })
    }, [current, pageSize])

    useImperativeHandle(ref, () => ({
        initPage: () => {
            current === 1 ? onChange && onChange({
                current,
                pageSize
            }) : setTablePage({ current: 1, pageSize: pageSizeInit })
        }
    }));

    return (
        <CustomizeTableContext.Provider
            value={{
                current,
                pageSize,
                tableKey,
                setTablePage: _setTablePage,
            }}
        >
            { children }
        </CustomizeTableContext.Provider>
    )
}

export default forwardRef(CustomizeTableProvide)

export const CustomizeTable = props => {
    const { columns, dataSource, pagination, selectionInfo = {}, expandable,  ...tableProps } = props
    const [ selections, setSelections ] = useState([])
    const { tableKey, current, pageSize } = useContext(CustomizeTableContext)
    const { keyValue, onChange: onSelectionChange, renderCell } = selectionInfo

    let dataSourceIds = keyValue ? dataSource.map(item => item[keyValue]).join(',') : []

    useEffect(() => {
        if (keyValue) {
            let _selection = selections.filter(item => dataSourceIds.includes(item[keyValue]))
            setSelections(_selection)
            onSelectionChange && onSelectionChange(_selection)
        }
    }, [dataSourceIds])

    let _dataSource = useMemo(() => {
        let addKey = list => list.map((item,index) => (expandable ? {
            ...item,
            key: keyValue ? item[keyValue] : (item.key || `${tableKey}_${current}_${index}`),
            ...(item[expandable.childrenColumnName || 'children']?.length ? {
                children: addKey(item[expandable.childrenColumnName || 'children'])
            } : {})
        } : {
            ...item,
            key: keyValue ? item[keyValue] : (item.key || `${tableKey}_${current}_${index}`),
        }))
        return addKey(pagination ? dataSource : dataSource.slice((current - 1) * pageSize, current * pageSize))
    }, [current, pageSize, dataSource]);

    const handleSelectionChange = useCallback((rowKeys, rows) => {
        setSelections(rows)
        onSelectionChange && onSelectionChange(rows)
    }, [])

    return (
        <Table
            className="customize-table"
            columns={columns}
            dataSource={_dataSource}
            pagination={false}
            expandable={{
                ...expandable,
                childrenColumnName: 'children'
            }}
            sticky
            {...(keyValue ? {
                rowSelection: {
                    selectedRowKeys: selections.map(item => item[keyValue]),
                    onChange: handleSelectionChange,
                    ...(renderCell ? {renderCell} : {})
                }
            } : {})}
            {...tableProps}
        />
    )
}

export const CustomizeOrderTable = props => {
    const { columns, dataSource, pagination, titleLineRender, productListKey = 'details'} = props
    const { current, pageSize, tableKey } = useContext(CustomizeTableContext)

    let _dataSource = useMemo(() => {
        let addKey = list => list.map((item,index) =>  ({
            ...item,
            key: `${tableKey}_${current}_${index}`,
        }))
        return addKey(pagination ? dataSource : dataSource.slice((current - 1) * pageSize, current * pageSize))
    }, [current, pageSize, dataSource]);
    return _dataSource.length ? _dataSource.map(data => (
        <OrderLine
            key={data.key}
            orderInfo={data}
            titleLine={titleLineRender(data)}
            columns={columns}
            productListKey={productListKey}
        />
    )) : <Empty className="pdt-48"/>
}

export const CustomizeTablePagination = props => {
    const { total } = props
    const { current, pageSize, setTablePage } = useContext(CustomizeTableContext)
    const onChange = (page, size) => {
        setTablePage({
            current: page,
            pageSize: size
        })
    }
    return (!total || total === 0) ? null : (
        <Pagination
            onChange={onChange}
            current={current}
            pageSize={pageSize}
            total={total}
            showSizeChanger={false}
            // pageSizeOptions={['10', '20', '50', '100']}
            // showTotal={(total, range) => `共 ${total} 条,当前 ${range[0]} - ${range[1]} 条`}
        />
    )
}